package com.lvyq.myplayer.ui.fragment.history

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.cache.PlayCacheAdapter
import com.lvyq.myplayer.adapter.history.PlayHistoryAdapter
import com.lvyq.myplayer.common.util.DataOperationUtils
import com.lvyq.myplayer.common.util.StartActivityUtils
import com.lvyq.myplayer.database.PlayerDatabase
import com.lvyq.myplayer.model.history.PlayHistoryViewModel
import com.lvyq.myplayer.model.history.PlayHistoryViewModelFactory
import com.lvyq.myplayer.parcelable.SongInfoData
import kotlinx.coroutines.launch

/**
 * 文件描述：SongPlayPagerFragment 最近播放-单曲
 * 作者：lvyq
 * 创建时间：2025-06-19
 * 修改时间：2025-06-19
 */
class SongPlayPagerFragment: Fragment() {
    private lateinit var historyAdapter: PlayHistoryAdapter

    private val playHistoryViewModel: PlayHistoryViewModel by viewModels {
        PlayHistoryViewModelFactory(PlayerDatabase.getDatabase(requireContext()).playHistoryDao())
    }
    private lateinit var commonView:RecyclerView
    var currentPlayLst :ArrayList<SongInfoData>?=null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
       return  initView()
    }

    private fun initView(): View? {
        var view  = View.inflate(context, R.layout.fragment_common_song,null)
        commonView=view.findViewById<RecyclerView>(R.id.commonView)
        commonView.layoutManager=LinearLayoutManager(context)
        initData()
        initListener()
        return view
    }

    private fun initListener() {

    }

    private fun initData() {
        historyAdapter= PlayHistoryAdapter()
        lifecycleScope.launch {
            var allPlayHistoryListFlow = playHistoryViewModel.getAllPlayHistoryListFlow(1)
            allPlayHistoryListFlow.collect{ lst->
                var list= ArrayList<SongInfoData>()
                lst.forEach {data->
                    list.add(SongInfoData(data.businessKey, data.bgImg,data.title,data.lrc,
                        data.url,data.singer,data.singerId,data.publishDate,data.albumId,data.albumName,null,0,null,null,null,null,null))

                }
                 currentPlayLst=list
                 historyAdapter.initData(list)
            }
        }
        historyAdapter.setOnItemClickListener(object : PlayHistoryAdapter.OnItemClickListener {
            override fun onItemClick(data: SongInfoData, position: Int) {
                //播放歌曲列表存储
                StartActivityUtils.startAudioPlayerActivityAndSaveDB(requireContext(), currentPlayLst,position)

            }
        })
        commonView.adapter=historyAdapter
    }


}